<template>
  <div v-if="num === 60" class="code-span code-btn" :class="{ disabled }" @click="start">
    获取验证码
  </div>
  <div v-else class="code-span">{{ num }}s</div>
</template>

<script>
import { fetchCode } from '@/api/supplier';

export default {
  props: {
    phone: {
      type: String,
      default: '',
    },
    fetchCode: {
      type: Function,
      default: fetchCode,
    },
  },
  data() {
    return {
      num: 60,
    };
  },
  computed: {
    disabled() {
      return !/^1\d{10}$/.test(this.phone);
    },
  },
  beforeUnmount() {
    this.clear();
  },
  methods: {
    async start() {
      if (this.disabled) return this.$toast('请正确输入手机号');
      await this.fetchCode({
        phone: this.phone,
      });
      this.startTimer();
    },
    startTimer() {
      if (this.num <= 0) {
        return (this.num = 60);
      }
      this.num = this.num - 1;
      setTimeout(() => {
        this.startTimer();
      }, 1000);
    },
    clear() {
      if (this.timer) clearTimeout(this.timer);
    },
  },
};
</script>

<style lang="less" scoped>
.code-span {
  color: #ff3649;
  font-size: 0.26rem;
  flex-shrink: 1;
  cursor: pointer;
  &.disabled {
    color: #c0c0c0;
  }
}
.code-btn {
  white-space: nowrap;
  line-height: 0.6rem;
  border-radius: 0.06rem;
}
</style>